#include "awi_dfu_pack.h"

int awi_dfu_pack_proc(uint8_t* buffer, int bytes, uint16_t dst, uint16_t src, uint16_t ctrl, const uint8_t *payload, uint16_t len)
{	
	if(bytes < AWI_DFU_PROTOCOL_HEADER_LENGTH) {
		return -1;
	}
	if(len > 0 && payload == NULL) {
		return -1;
	}
	if(NULL == buffer) {
		return -1;
	}
	
	struct _dfu_header * header = (struct _dfu_header*)buffer;
	header->magic = awi_htons(AWI_DFU_PROTOCOL_MAGIC_NUMBER);
	header->version = awi_ntohs(AWI_DFU_PROTOCOL_VERSION);
	header->dst = awi_htons(dst);
	header->src = awi_htons(src);
	header->ctrl = awi_htons(ctrl);
	header->len = awi_htons(len);
	header->crc = 0;
	if(header->len > 0) {
		memcpy(buffer + AWI_DFU_PROTOCOL_HEADER_LENGTH, payload, len);
	}
	header->crc = awi_htons(crc_xmodem((const unsigned char*)buffer, len + AWI_DFU_PROTOCOL_HEADER_LENGTH));
	return len + AWI_DFU_PROTOCOL_HEADER_LENGTH;
}

int awi_dfu_pack_header(uint8_t *buffer, uint16_t dst, uint16_t src, uint16_t ctrl, uint16_t len)
{
	if(NULL == buffer) {
		return -1;
	}
	struct _dfu_header * header = (struct _dfu_header*)buffer;
	header->magic = awi_htons(AWI_DFU_PROTOCOL_MAGIC_NUMBER);
	header->version = awi_ntohs(AWI_DFU_PROTOCOL_VERSION);
	header->dst = awi_htons(dst);
	header->src = awi_htons(src);
	header->ctrl = awi_htons(ctrl);
	header->len = awi_htons(len);
	header->crc = 0;
	header->crc = awi_htons(crc_xmodem((const unsigned char*)buffer, len + AWI_DFU_PROTOCOL_HEADER_LENGTH));
	return 0;
}